<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\KnowledgeExistsException;
use App\Exceptions\KnowledgeNotFoundException;
use App\Exceptions\KnowledgeUsedException;
use App\Models\Attachment;
use App\Models\Knowledge;

class KnowledgeController extends Controller
{
    /*
     * @api get /course-api/a/knowledge 知识点列表
     * @version 0.0.1
     * @group admin
     *
     * @param query int [pageSize] 页数，默认15
     * @param query int [page] 页码，默认1
     * @param query string [name] 名称
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *    "items":[]
     * }
     * }
     */
    public function index()
    {
        $this->validate($this->request, [
            'pageSize' => "integer|max:100|min:5",
            'page' => "integer|min:1",
            'name' => 'string'
        ]);

        $page = intval($this->request->input("page", 1));
        $pageSize = intval($this->request->input("pageSize", 15));
        $name = $this->request->input('name');
        $query = Knowledge::query();

        if (isset($name)) {
            $query->where('en_name', 'like', "%{$name}%")
            ->orWhere('cn_name', 'like', "%{$name}%");
        }

        $total = $query->count();
        $knowledgesObj = $query->orderBy('id', 'desc')->forPage($page, $pageSize)
            ->get();
        $items = [];
        if ($total) {
            /** @var Knowledge $knowledgeObj */
            foreach ($knowledgesObj as $knowledgeObj) {
                $items[] = [
                    'id' => $knowledgeObj->getId(),
                    'name' => $knowledgeObj->getName(),
                    'partOfSpeech' => $knowledgeObj->getPartOfSpeech(),
                    'chinese' => $knowledgeObj->getChinese(),
                ];
            }
        }
        return $this->sendSuccessJson(['total'=>$total, 'items'=>$items]);
    }

    /*
     * @api post /course-api/a/knowledge 新增知识点
     * @version 0.0.1
     * @group admin
     *
     * @param body string name 名称
     * @param body string chinese 中文
     * @param body array syllable 音节
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":"id"
     * }
     */
    public function store()
    {
        $this->validate($this->request, [
            'name' => 'required|string',
            'chinese' => 'required|string',
            'partOfSpeech' => 'required|string',
            'audioId' => 'required|integer',
            'tagIds' => 'required|array',
            'images' => 'required|array'
        ]);
        $name = $this->request->input('name');
        $chinese = $this->request->input('chinese');
        $partOfSpeech = $this->request->input('partOfSpeech');
        $tagIds = $this->request->input('tagIds');
        $audioId = $this->request->input('audioId');
        $images = $this->request->input('images');
        if (Knowledge::where('en_name', $name)->where('part_of_speech', $partOfSpeech)->exists()) {
            throw new KnowledgeExistsException();
        }
        $knowledgeObj = new Knowledge();
        $knowledgeObj->setName($name);
        $knowledgeObj->setChinese($chinese);
        $knowledgeObj->setPartOfSpeech($partOfSpeech);
        $knowledgeObj->setTagId($tagIds[0]);
        $knowledgeObj->setAudio($audioId);
        $knowledgeObj->setImages($images);
        $knowledgeObj->save();
        return $this->sendSuccessJson($knowledgeObj->getId());
    }


    /*
     * @api put /course-api/a/knowledge/{knowledgeId} 更新知识点
     * @version 0.0.1
     * @group admin
     *
     * @param path int knowledgeId 知识点ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *    "items":[]
     * }
     * }
     */
    public function update($knowledgeId)
    {
        $this->request->merge(['id'=>$knowledgeId]);
        $this->validate($this->request, [
            'id' => 'required|integer',
            'name' => 'required|string',
            'chinese' => 'required|string',
            'partOfSpeech' => 'required|string',
            'audioId' => 'required|integer',
            'tagIds' => 'required|array',
            'images' => 'required|array'
        ]);
        $name = $this->request->input('name');
        $chinese = $this->request->input('chinese');
        $partOfSpeech = $this->request->input('partOfSpeech');
        $tagIds = $this->request->input('tagIds');
        $audioId = $this->request->input('audioId');
        $images = $this->request->input('images');
        $existsId = Knowledge::where('en_name', $name)->where('part_of_speech', $partOfSpeech)->value('id');
        if ($existsId && $existsId != $knowledgeId) {
            throw new KnowledgeExistsException();
        }
        /** @var Knowledge $knowledgeObj */
        $knowledgeObj = Knowledge::find($knowledgeId);
        if (!$knowledgeObj) {
            throw new KnowledgeNotFoundException();
        }
        $knowledgeObj->setName($name);
        $knowledgeObj->setChinese($chinese);
        $knowledgeObj->setPartOfSpeech($partOfSpeech);
        $knowledgeObj->setTagId($tagIds[0]);
        $knowledgeObj->setAudio($audioId);
        $knowledgeObj->setImages($images);
        $knowledgeObj->save();
        return $this->sendSuccessJson($knowledgeObj->getId());
    }

    /*
     * @api get /course-api/a/knowledge/{knowledgeId} 知识点详情
     * @version 0.0.1
     * @group admin
     *
     * @param path int knowledgeId 知识点ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *    "items":[]
     * }
     * }
     */
    public function show($knowledgeId)
    {
        $knowledgeId = intval($knowledgeId);
        /** @var Knowledge $knowledgeObj */
        $knowledgeObj = Knowledge::find($knowledgeId);
        if (!$knowledgeObj) {
            throw new KnowledgeNotFoundException();
        }
        $images = $knowledgeObj->getImages();
        $imagesInfo = [];
        foreach ($images as $image) {
            /** @var Attachment $imageObj */
            $imageObj = Attachment::find($image['id']);
            $imagesInfo[] = [
                'id' => $imageObj->id,
                'name' => $imageObj->getName(),
                'uri' => $imageObj->getUri(),
                'ext' => $imageObj->getExt(),
                'isCover' => $image['isCover'] ?? false
            ];
        }
        $item = [
            'id' => $knowledgeObj->getId(),
            'partOfSpeech' => $knowledgeObj->getPartOfSpeech(),
            'images' => $imagesInfo,
            'name' => $knowledgeObj->getName(),
            'chinese' => $knowledgeObj->getChinese(),
            'audio' => $knowledgeObj->audio()->first(['id', 'name', 'uri', 'ext']),
            'tags' => []
        ];
        $item['tags'] = [];
        $tag = $knowledgeObj->tag()->first();
        if ($tag) {
            $item['tags'][] = [
                'id' => $tag->getId(),
                'cnName' => $tag->getCnName(),
                'enName' => $tag->getEnName(),
                'description' => $tag->getDescription()
            ];
        }
        return $this->sendSuccessJson($item);
    }

    /*
     * @api delete /course-api/a/knowledge/{knowledgeId} 删除知识点
     * @version 0.0.1
     * @group admin
     *
     * @param path int knowledgeId 知识点ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *    "items":[]
     * }
     * }
     */
    public function destroy($knowledgeId)
    {
        $knowledgeId = intval($knowledgeId);
        /** @var Knowledge $knowledgeObj */
        $knowledgeObj = Knowledge::find($knowledgeId);
        if (!$knowledgeObj) {
            throw new KnowledgeNotFoundException();
        }
        if ($knowledgeObj->lesson()->exists()) {
            throw new KnowledgeUsedException();
        }
        Knowledge::destroy($knowledgeId);
        return $this->sendSuccessJson();
    }
}
